﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;

namespace FYPHP
{
    public partial class ShopCart : System.Web.UI.Page
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["fyphp"].ConnectionString);

        protected void Page_Load(object sender, EventArgs e)
        {
                if (Session["Username"].ToString() != null && Session["ID"].ToString() != null)
                {
                    Panel1.Visible = true;
                    lblUserName.Text = Session["Username"].ToString();
                    lblUserID.Text = Session["ID"].ToString();
                    lblUserID.Visible = false;
                }
                else
                {
                    Panel1.Visible = false;
                }
            
                SqlCommand cmdSearch;
                SqlDataReader dtrSearch;
                conn.Open();

                cmdSearch = new SqlCommand("SELECT * FROM Transactions t, Users u WHERE t.t_seller = u.u_id AND t_status = 'Cart' AND t.u_id = @id", conn);
                cmdSearch.Parameters.AddWithValue("@id", lblUserID.Text);
                dtrSearch = cmdSearch.ExecuteReader();

                Repeater1.DataSource = dtrSearch;
                Repeater1.DataBind();

                dtrSearch.Close();
                conn.Close();
        }

        private void MessageBox(string msg)
        {
            Label lbl = new Label();
            lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('" + msg + "')</script>";
            Page.Controls.Add(lbl);
        }

        private void Redirect(string msg)
        {
            Label lbl = new Label();
            lbl.Text = "<script language=\"javascript\">window.location='" + msg + "';</script>";
            Page.Controls.Add(lbl);
        }

        public double processData(object quantity, object price)
        {
            double total = int.Parse(quantity.ToString()) * double.Parse(price.ToString());
            return total;
        }

        protected void ItemList_ItemCommand(Object Sender, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "ViewCart")
            {
                int id = Convert.ToInt32(e.CommandArgument.ToString());
                SqlCommand cmdProduct;
                SqlDataReader dtrProduct;
                conn.Open();

                cmdProduct = new SqlCommand("SELECT * FROM Products p, Transactions t,Transactions_Products tp WHERE tp.p_id=p.p_id AND tp.t_id=t.t_id AND t.t_id=@id and t.t_status=@Status", conn);
                cmdProduct.Parameters.AddWithValue("@id", id);
                cmdProduct.Parameters.AddWithValue("@Status", "Cart");
                dtrProduct = cmdProduct.ExecuteReader();

                ShoppingCartItemList.DataSource = dtrProduct;
                ShoppingCartItemList.DataBind();

                dtrProduct.Close();
                dtrProduct = cmdProduct.ExecuteReader();

                dtrProduct.Read();
                String TotalOrder = dtrProduct["t_total"].ToString();

                lblTotal.Text = TotalOrder;

                dtrProduct.Close();
                conn.Close();

                MultiView1.ActiveViewIndex = 0;
            }
            else if (e.CommandName == "DeleteCart")
            {
                int id = Convert.ToInt32(e.CommandArgument.ToString());
                SqlCommand dltProduct;
                conn.Open();

                dltProduct = new SqlCommand("DELETE FROM Transactions_Products WHERE t_id=@id", conn);
                dltProduct.Parameters.AddWithValue("@id", id);
                dltProduct.ExecuteNonQuery();

                dltProduct = new SqlCommand("DELETE FROM Transactions WHERE t_id=@id", conn);
                dltProduct.Parameters.AddWithValue("@id", id);
                dltProduct.ExecuteNonQuery();

                conn.Close();
                MessageBox("Delete successfully!");
                Redirect("ShopCart.aspx");
            }
            else if (e.CommandName == "CheckOut")
            {
                int id = Convert.ToInt32(e.CommandArgument.ToString());
                SqlCommand cmdProduct;
                SqlDataReader dtrProduct;
                conn.Open();

                cmdProduct = new SqlCommand("SELECT * FROM Transactions WHERE t_id=@id", conn);
                cmdProduct.Parameters.AddWithValue("@id", id);
                dtrProduct = cmdProduct.ExecuteReader();

                dtrProduct.Read();

                double total = Convert.ToDouble(dtrProduct["t_total"].ToString());
                String t_seller = dtrProduct["t_seller"].ToString();

                dtrProduct.Close();
                conn.Close();

                Session["TotalOrder"] = total;
                Session["ReferenceNumber"] = "REF" + String.Format("{0:00000}", id);
                Session["SellerID"] = t_seller;
                Session["TransactionID"] = id;

                Response.Redirect("ShippingDetail.aspx");
            }
           
        }

        protected void ShopCart_ItemCommand(Object Sender, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "DeleteCartItem")
            {
                int id = Convert.ToInt32(e.CommandArgument.ToString());
                SqlCommand dltProduct,checkProduct,checkProductPrice,updateTotalTransaction,cmdCheckTransactionTotal,cmdCheckAvailableOfTransactionProduct,cmdDeleteTransaction;
                SqlDataReader dtrcheckProduct;
                conn.Open();

              
               
                //Obtained PID , TID and Quantity

                checkProduct = new SqlCommand("Select * FROM Transactions_Products WHERE tp_id=@id",conn);
                checkProduct.Parameters.AddWithValue("@id", id);
                dtrcheckProduct = checkProduct.ExecuteReader();

                dtrcheckProduct.Read();

                String p_id = dtrcheckProduct["p_id"].ToString();
                String t_id = dtrcheckProduct["t_id"].ToString();
                String quantity = dtrcheckProduct["quantity"].ToString();
                

                dtrcheckProduct.Close();

                cmdCheckAvailableOfTransactionProduct = new SqlCommand("Select COUNT(tp_id) FROM Transactions_Products WHERE t_id=@id", conn);
                cmdCheckAvailableOfTransactionProduct.Parameters.AddWithValue("@id", t_id);
                int check = Convert.ToInt32(cmdCheckAvailableOfTransactionProduct.ExecuteScalar());

                //Obtained the product price
                checkProductPrice = new SqlCommand("Select p_price FROM Products WHERE p_id=@PID", conn);
                checkProductPrice.Parameters.AddWithValue("@PID",p_id);
                double p_price = Convert.ToDouble(checkProductPrice.ExecuteScalar());


                //Obtained the old TotalOrder
                cmdCheckTransactionTotal = new SqlCommand("Select t_total FROM Transactions WHERE t_id =@TID",conn);
                cmdCheckTransactionTotal.Parameters.AddWithValue("@TID",t_id);
                double oldTotal = Convert.ToDouble(cmdCheckTransactionTotal.ExecuteScalar());

                //Update new Total
                updateTotalTransaction = new SqlCommand("Update Transactions SET t_total=@Total where t_id=@TID",conn);
                updateTotalTransaction.Parameters.AddWithValue("@Total",Convert.ToDouble(oldTotal)-(Convert.ToDouble(quantity)*Convert.ToDouble(p_price)));
                updateTotalTransaction.Parameters.AddWithValue("@TID",t_id);
                updateTotalTransaction.ExecuteNonQuery();


                //Delete the particular product
                dltProduct = new SqlCommand("DELETE FROM Transactions_Products WHERE tp_id=@id", conn);
                dltProduct.Parameters.AddWithValue("@id", id);
                dltProduct.ExecuteNonQuery();

                //If there is only last product in the cart
                if (check == 1) 
                {
                    cmdDeleteTransaction = new SqlCommand("DELETE FROM Transactions WHERE t_id=@id", conn);
                    cmdDeleteTransaction.Parameters.AddWithValue("@id",t_id);
                    cmdDeleteTransaction.ExecuteNonQuery();
                }
                conn.Close();
                MessageBox("Delete successfully!");
                Redirect("ShopCart.aspx");
            }
        }
    }
}